package com.rytx.web.controller.ysp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.github.pagehelper.util.StringUtil;
import com.rytx.common.config.MyAliPayConfig;
import com.rytx.common.core.controller.BaseController;
import com.rytx.common.core.domain.AjaxResult;
import com.rytx.common.core.domain.R;
import com.rytx.common.core.domain.entity.SysDictData;
import com.rytx.common.core.domain.model.ArtUser;
import com.rytx.common.core.domain.model.LoginUser;
import com.rytx.common.core.page.TableDataInfo;
import com.rytx.common.core.redis.ArtRedisUtils;
import com.rytx.common.core.redis.RedisQueueService;
import com.rytx.common.utils.alipay.AlipayConfigUtil;
import com.rytx.common.utils.ip.IpUtils;
import com.rytx.framework.web.service.SysLoginService;
import com.rytx.system.domain.Cnarea2023;
import com.rytx.system.domain.ShippingAddresses;
import com.rytx.system.domain.vo.CartArtOrder;
import com.rytx.system.domain.ysp.*;
import com.rytx.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.*;

@RestController
@RequestMapping("/ysp")
@Api(value = "YspController", tags = {"不需要登录的接口"})
public class YspController  extends BaseController {

    @Resource
    private IArtUserService artUserService;
    @Resource
    private SysLoginService loginService;
    @Resource
    private MyAliPayConfig myAliPayConfig;
    @Resource
    private IArtCarouselItemService artCarouselItemService;
    @Resource
    private IArtRentalService artRentalService;
    @Resource
    private IArtOrderService artOrderService;
    @Resource
    private IShippingAddressesService shippingAddressesService;
    @Resource
    private ArtRedisUtils artRedisUtils;
    @Resource
    private RedisQueueService<String> redisQueueService;
    @Resource
    private ICnarea2023Service cnarea2023Service;

    @Resource
    private ISysDictDataService sysDictDataService;

    @Resource
    private ArtKdCompanyService artKdCompanyService;

    @Resource
    private ArtCommonConfigService artCommonConfigService;

    /**
     * 添加查看数
     * @param
     * @return
     */
    @GetMapping("/orderInfo/{orderNo}")
    public AjaxResult orderInfo(@PathVariable("orderNo") String orderNo)
    {
        ArtOrder order = artOrderService.getOrderByOrderNo(orderNo);
        Map<String, Object> map = new HashMap<>();
        map.put("order", order);
        List<ArtRental> artRentals = new ArrayList<>();
        for(String id : order.getCartRentalIds().split(",")){
            artRentals.add(artRentalService.selectArtRentalById(Long.parseLong(id)));
        }
        map.put("artRentals", artRentals);
        return AjaxResult.success(map);
    }

    /**
     * 添加查看数
     * @param
     * @return
     */
    @GetMapping("/addViewHistory/{id}")
    public AjaxResult addViewHistory(@PathVariable("id") Long id)
    {
        return artRentalService.addViewHistory(id);
    }

    /**
     * 首页轮播订单
     * @param
     * @return
     */
    @GetMapping("/appCarouselList")
    public TableDataInfo appCarouselList()
    {
        startPage();
        List<ArtOrder> list = artOrderService.appCarouselList();
        List<Map<String, Object>> listMap = new ArrayList<>();
        for(ArtOrder artOrder : list){
            Map<String, Object> map = new HashMap<>();
            map.put("order", artOrder);
            String artistName = "";
            List<ArtRental> artRentals = new ArrayList<>();
            if(artOrder.getCartRentalIds() != null && !"".equals(artOrder.getCartRentalIds())){
                artRentals = artRentalService.selectArtRentalByIds(artOrder.getCartRentalIds());
                for(ArtRental artRental : artRentals){
                    artistName += artRental.getArtistName() + ",";
                }
                artistName = artistName.substring(0, artistName.length() - 1);
            }
            map.put("artistName", artistName);
            listMap.add(map);
        }
        return getDataTable(listMap);
    }

    @GetMapping("/wxSwitch")
    @ApiOperation(value = "微信开关", notes = "微信开关")
    public AjaxResult wxSwitch() {
        SysDictData sysDictData = sysDictDataService.selectDictDataByType("wx_switch");
        return AjaxResult.success(sysDictData.getDictValue());
    }

    //登录页
    @GetMapping("/customerServiceMobile")
    @ApiOperation(value = "查询客服电话", notes = "查询客服电话")
    public AjaxResult customerServiceMobile() {
        SysDictData sysDictData = sysDictDataService.selectDictDataByType("customer_service_mobile");
        return AjaxResult.success(sysDictData.getDictValue());
    }

    //登录页
    @GetMapping("/ali/userinfo")
    public AjaxResult userinfo(String authCode) throws AlipayApiException {
        if(StrUtil.isBlank(authCode)) return  AjaxResult.error("授权码不能为空");
        return AjaxResult.success("登录成功", loginService.ailLogin(authCode));
    }
    //登录页
    @GetMapping("/wx/wxUserinfo")
    public AjaxResult wxUserinfo(String authCode) throws AlipayApiException {
        if(StrUtil.isBlank(authCode)) return  AjaxResult.error("授权码不能为空");
        return AjaxResult.success("登录成功", loginService.wxLogin(authCode));
    }
    @GetMapping("/art/userinfo")
    public AjaxResult artUserLogin(String authCode) throws AlipayApiException {
        if(StrUtil.isBlank(authCode)) return  AjaxResult.error("授权码不能为空");
        Map<String, Object> stringObjectMap = loginService.aliLogin(authCode);
        if("".equals(stringObjectMap.get("token"))||stringObjectMap.get("token") == null){
            return AjaxResult.error("登录失败",stringObjectMap);
        }else{
            return AjaxResult.success("登录成功",stringObjectMap);
        }
    }

    /**
     * 支付宝支付追缴订单
     *
     * @param order 订单信息
     * @return R<String>
     */
    @PostMapping("/recoveryOrder")
    public R<String> recoveryOrder(ArtOrder order) {
        LoginUser loginUser = getLoginUser();
        if(loginUser.getArtUser() == null){
            return R.fail("用户未登录");
        }
        Long userid = loginUser.getArtUser().getId();
        if(userid == null){
            return R.fail("用户未找到");
        }

        order.setUserId(userid);
        String result = artOrderService.getRecoveryOrderTradeNo(order);
        if("fail".equals(result)){
            return R.fail("获取trade_no失败");
        }
        return R.ok(result);
    }
    /**
     * 创建租赁订单
     *
     * @param order 订单信息
     * @return R<String>
     */
    @PostMapping("/order")
    public R<String> order(ArtOrder order) {
        LoginUser loginUser = getLoginUser();
        if(loginUser.getArtUser() == null){
            return R.fail("用户未登录");
        }
        Long userid = loginUser.getArtUser().getId();
        if(userid == null){
            return R.fail("用户未找到");
        }
        // 请求的地址
        String payType = order.getPayType();
        String ip = IpUtils.getIpAddr();
        order.setIp(ip);
        if(StringUtil.isEmpty(payType)){
            payType = "1";
        }

        order.setUserId(userid);

        String lockKey = "lock:" + order.getArtRentalId();
        // 请求的唯一ID，可以使用UUID等
        String requestId = UUID.randomUUID().toString();
        // 锁的过期时间
        long expireTime = 10;
        if (artRedisUtils.tryLock(lockKey, requestId, expireTime)) {
            logger.info("{}:获取锁成功",lockKey);
            try {
                if("1".equals(order.getOrderType())){ // 租赁订单
                    if("0".equals(order.getLeaseType())){ // 免押
                        return R.ok(artOrderService.createOrder(order));
                    }else{ // 普通支付
                        return R.ok(artOrderService.createLeaseBuyOrder(order));
                    }

                } else if ("2".equals(order.getOrderType())) { // 购买订单
                    return R.ok(artOrderService.buyOrder(order));
                }
            }catch (Exception e){
                logger.error("创建订单异常", e);
                return R.fail("创建失败");
            }finally {
                // 业务逻辑执行完毕，释放锁
                boolean unlock = artRedisUtils.unlock(lockKey, requestId);
                logger.info("{}:释放锁：{}",lockKey, unlock);
            }
        } else {
            return R.fail("创建失败");
        }
        return null;
    }

    /**
     * 创建购物车订单
     * 1支付宝 如果没有输入payType则默认使用支付宝
     * 2微信
     * payType
     * @param
     * @return R<String>
     */
    @PostMapping("/cartOrder")
    public R<String> cartOrder(@RequestBody CartArtOrder orders) {
        String payType = orders.getPayType();
        // 请求的地址
        String ip = IpUtils.getIpAddr();
        if(StringUtil.isEmpty(payType)){
            payType = "1";
        }
        LoginUser loginUser = getLoginUser();
        if(loginUser.getArtUser() == null){
            return R.fail("用户未登录");
        }
        Long userid = loginUser.getArtUser().getId();
        if(userid == null){
            return R.fail("用户未找到");
        }

        if(null == orders){
            return R.fail("订单信息异常");
        }
        List<ArtOrder> artOrders = orders.getArtOrders();
        if(null == artOrders || artOrders.size() == 0){
            return R.fail("订单信息异常");
        }
        for(ArtOrder artOrder : artOrders){
            artOrder.setUserId(userid);
            artOrder.setOrderType("2");
        }

        ArtOrder artOrder = artOrders.get(0);
        String lockKey = "lock:" + artOrder.getArtRentalId();
        // 请求的唯一ID，可以使用UUID等
        String requestId = UUID.randomUUID().toString();
        // 锁的过期时间
        long expireTime = 10;
        if (artRedisUtils.tryLock(lockKey, requestId, expireTime)) {
            logger.info("{}:获取锁成功",lockKey);
            try {
                 // 购买订单
                    return R.ok(artOrderService.cartByOrder(orders,userid,payType,ip));
            }catch (Exception e){
                logger.error("创建订单异常", e);
                return R.fail("创建失败");
            }finally {
                // 业务逻辑执行完毕，释放锁
                boolean unlock = artRedisUtils.unlock(lockKey, requestId);
                logger.info("{}:释放锁：{}",lockKey, unlock);
            }
        } else {
            return R.fail("创建失败");
        }

    }

    /**
     * 支付宝订单查询接口
     * */
    @PostMapping("/order/query")
    public AjaxResult getAilOrderInfo(String orderNo) throws AlipayApiException {
        ArtOrder artOrder = new ArtOrder();
        artOrder.setOrderNo(orderNo);
        artOrder = artOrderService.selectArtOrderByParam(artOrder);
        if(BeanUtil.hasNullField(artOrder, "id")){
            return AjaxResult.error("订单不存在");
        }

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        AlipayFundAuthOperationDetailQueryRequest request = new AlipayFundAuthOperationDetailQueryRequest();
        JSONObject bizContent = new JSONObject();
        // out_order_no与auth_no选择其一传入即可
        bizContent.put("out_order_no","outOrderNo123");
        // bizContent.put("auth_no","2021081710002001640564315836");
        // out_request_no与operation_id选择其一传入即可
        bizContent.put("out_request_no","outRequestNo123");
        // bizContent.put("operation_id","20161012405744018102");
        bizContent.put("operation_type","FREEZE");  //冻结: FREEZE 解冻: UNFREEZE 支付: PAY
        //如果使用风控专业版查询异步风控数据是需要传入以下参数
        // List queryOptions = new ArrayList<>();
        // queryOptions.add("credit_risk_info");
        //bizContent.put("query_options",queryOptions);
        // 设置整体请求参数
        request.setBizContent(bizContent.toString());
        // 使用execute方法发起请求
        AlipayFundAuthOperationDetailQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return AjaxResult.success("查询成功",response.getBody());
    }
    /**
     * 取消订单
     * */
    @PostMapping("/order/cancel")
    public void deleteOrder(String orderNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        AlipayFundAuthOperationCancelRequest request = new AlipayFundAuthOperationCancelRequest();

        JSONObject bizContent = new JSONObject();

        // out_order_no与auth_no选择其一传入即可
        bizContent.put("out_order_no","outOrderNo123");
        //auth_no在授权冻结成功时返回参数中获得
        // bizContent.put("auth_no","2021081710002001640564315836");

        // out_request_no与operation_id选择其一传入即可
        //out_request_no与冻结流水号相同
        bizContent.put("out_request_no","outRequestNo123");
        // bizContent.put("operation_id","20161012405744018102");

        // 商家对本次撤销操作的附言描述，长度不超过100个字母或50个汉字
        bizContent.put("remark","撤销授权");

        // 设置整体请求参数
        request.setBizContent(bizContent.toString());

        // 使用execute方法发起请求
        AlipayFundAuthOperationCancelResponse response = alipayClient.execute(request);

        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
    //扣款
    @PostMapping("/order/pay")
    public void orderPay() throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no","ZMMY20240515153134");//扣款商户订单号，为商家的交易流水号
        bizContent.put("total_amount","0.01");//结算支付金额
        bizContent.put("product_code","PREAUTH_PAY");//根据开通支付产品传参；开通预授权支付产品传 PREAUTH_PAY，开通支付宝预授权产品传 PRE_AUTH_ONLINE
        bizContent.put("auth_no","2024051510002001340574714108");//芝麻免押授权订单号
        bizContent.put("auth_confirm_mode","NOT_COMPLETE");//确认模式
        bizContent.put("enable_pay_channels","point,mdiscount");//商户如果有需要指定扣款渠道的情况或者模拟扣款失败的时候需要指定扣款渠道的时候可以通过该参数传入渠道。
        Map<String,String> businessParams = new HashMap<>();
        businessParams.put("deduction_subject","SERVICE_FEE");//在新的免押受理台模式中，商户需要指定自己扣费类型
        bizContent.put("business_params",businessParams);

        request.setBizContent(bizContent.toString());
        request.setNotifyUrl(myAliPayConfig.getNotifyUrl());//异步通知地址
        AlipayTradePayResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());
        } else {
            System.out.println("调用失败");
        }
    }

    @PostMapping("/order/pay/byr")
    public  void orderPayByR(ArtOrder order) throws AlipayApiException {
        ArtOrder artOrder = artOrderService.selectArtOrderById(order.getId());
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        // 构造请求参数以调用接口
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        AlipayTradePayModel model = new AlipayTradePayModel();
        // 设置商户门店编号
        model.setStoreId("NJ_001");
        // 设置业务扩展参数
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088511833207846");
        extendParams.setSpecifiedSellerName("XXX的跨境小铺");
        extendParams.setCardType("S0JP0000");
        //model.setExtendParams(extendParams);
        // 设置商户订单号
        model.setOutTradeNo("ZMMY20240515153134");
        // 设置返回参数选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("voucher_detail_list");
        //model.setQueryOptions(queryOptions);
        // 设置订单总金额
        model.setTotalAmount("0.01");
        // 设置预授权确认模式
        model.setAuthConfirmMode("COMPLETE");
        // 设置订单标题
        model.setSubject("测试订单2024-05-15租金");
        // 设置产品码
        model.setProductCode("PREAUTH_PAY");
        // 设置订单包含的商品列表信息
        List<GoodsDetail> goodsDetail = new ArrayList<GoodsDetail>();
        GoodsDetail goodsDetail0 = new GoodsDetail();
        goodsDetail0.setGoodsName("艺术品01");
        goodsDetail0.setQuantity(1L);
        goodsDetail0.setPrice("0.01");
        goodsDetail0.setGoodsId("ysp-01");
//        goodsDetail0.setGoodsCategory("34543238");
//        goodsDetail0.setCategoriesTree("124868003|126232002|126252004");
//        goodsDetail0.setShowUrl("http://www.alipay.com/xxx.jpg");
        goodsDetail.add(goodsDetail0);
        //model.setGoodsDetail(goodsDetail);
        // 设置资金预授权单号
        model.setAuthNo("2024051510002001340574714108");
        // 设置优惠明细参数
        PromoParam promoParams = new PromoParam();
        promoParams.setActualOrderTime("2018-09-25 22:47:33");
       // model.setPromoParams(promoParams);
        // 设置商户机具终端编号
       // model.setTerminalId("NJ_T_001");
        request.setBizModel(model);
        AlipayTradePayResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

    }

    /**
     * 查询扣款结果
     *
     * */
    @PostMapping("/orderpay/query")
    public void getOrderPay() throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient =  new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));

        // 构造请求参数以调用接口
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();

        // 设置订单支付时传入的商户订单号
        model.setOutTradeNo("20150320010101001");

        // 设置银行间联模式下有用
        model.setOrgPid("2088101117952222");

        // 设置查询选项
        List<String> queryOptions = new ArrayList<String>();
        queryOptions.add("trade_settle_info");
        model.setQueryOptions(queryOptions);

        // 设置支付宝交易号
        model.setTradeNo("2014112611001004680 073956707");

        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }

    /**
     * 完结订单
     */
    public void orderFinish() throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        AlipayFundAuthOrderUnfreezeRequest request = new AlipayFundAuthOrderUnfreezeRequest();

        JSONObject bizContent = new JSONObject();

        bizContent.put("auth_no", "2021081710002001640564315836");
        bizContent.put("out_request_no", "outRequestNo123");
        bizContent.put("amount", 0.01);
        bizContent.put("remark", "解冻资金");

        JSONObject extraParam = new JSONObject();
        JSONObject unfreezeBizInfo = new JSONObject();
        unfreezeBizInfo.put("bizComplete", true);
        extraParam.put("unfreezeBizInfo", unfreezeBizInfo);
        bizContent.put("extra_param", extraParam);

        // 设置整体请求参数
        request.setBizContent(bizContent.toString());

        // 使用execute方法发起请求
        AlipayFundAuthOrderUnfreezeResponse response = alipayClient.execute(request);

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }


    }

    /**
     * redis队列
     * @param quname 队列名
     * @param qvalue 队列值
     */
    @GetMapping("/enqueue")
    public AjaxResult queue(String quname,String qvalue){
        return AjaxResult.success(redisQueueService.enqueue(quname, qvalue));
    }

    /**
     * 获取队列
     * @param qu 队列名
     * @return 队列值
     */
    @GetMapping("/dequeue")
    public AjaxResult dequeue(String qu){
        return AjaxResult.success(redisQueueService.dequeue(qu)) ;
    }
    //我的足迹页
    @PostMapping("/footprint")
    public void footprint(){

    }
    //地址管理页
    @PostMapping("/address")
    public AjaxResult address(@RequestBody ShippingAddresses shippingAddresses){
       return AjaxResult.success(shippingAddressesService.insertShippingAddresses(shippingAddresses));
    }
    //地址
    @GetMapping("/regions")
    public AjaxResult regions(Cnarea2023 cnarea2023){
        return AjaxResult.success(cnarea2023Service.selectCnarea2023List(cnarea2023));
    }
    //用户信息
    @PostMapping("/userinfo")
    public R<ArtUser> userInfo(String openid) {
        ArtUser artUser = artUserService.selectArtUserByAliOpenid(openid);
        ArtUser newArtUser = new ArtUser();
        newArtUser.setAliOpenId(artUser.getAliOpenId());
        newArtUser.setUserName(artUser.getUserName());
        newArtUser.setUserPhone(artUser.getUserPhone());
        newArtUser.setNickName(artUser.getNickName());
        newArtUser.setUserAvatarUrl(artUser.getUserAvatarUrl());
        return R.ok(newArtUser);
    }

    //用户信息
    @PostMapping("/WXuserInfo")
    public R<ArtUser> WXuserInfo(String openid) {
        ArtUser artUser = artUserService.selectArtUserByWxOpenid(openid);
        ArtUser newArtUser = new ArtUser();
        newArtUser.setAliOpenId(artUser.getWxOpenId());
        newArtUser.setUserName(artUser.getUserName());
        newArtUser.setUserPhone(artUser.getUserPhone());
        newArtUser.setNickName(artUser.getNickName());
        newArtUser.setUserAvatarUrl(artUser.getUserAvatarUrl());
        return R.ok(newArtUser);
    }

    //修改用户信息
    @PutMapping("/editUserInfo")
    public AjaxResult editUserInfo(@RequestBody ArtUser artUser)
    {
        return toAjax(artUserService.updateArtUserByAliOpenid(artUser));
    }
    //获取轮播图
    @GetMapping("/itemList")
    public TableDataInfo list(ArtCarouselItem artCarouselItem)
    {
        startPage();
        artCarouselItem.setStatus("1");
        List<ArtCarouselItem> list = artCarouselItemService.selectArtCarouselItemList(artCarouselItem);
        return getDataTable(list);
    }

    @PostMapping("/art/list")
    public TableDataInfo list(@RequestBody ArtRental artRental)
    {
        startPage();
        artRental.setRentalStatus("1");//已上架
        List<ArtRental> list = artRentalService.selectArtRentalListByPro(artRental);
        return getDataTable(list);
    }


    @GetMapping(value = "/art/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(artRentalService.selectArtRentalById(id));
    }

    public TableDataInfo getOrderList(ArtOrder order){
        startPage();
        List<ArtOrder> list = artOrderService.selectArtOrderList(order);
        return getDataTable(list);
    }

    @GetMapping(value = "/copywriting/{id}")
    public AjaxResult copywriting(@PathVariable("id") String id)
    {
        if("0".equals(id)){
            return success(artCommonConfigService.getAllConfigs());
        }
        ArtCommonConfig artCommonConfig = new ArtCommonConfig();
        artCommonConfig.setConfigType(id);
        return success(artCommonConfigService.searchConfigs(artCommonConfig));
    }

    //获取所有快递公司列表
    @GetMapping("/artKdCompanyList")
    public List<ArtKdCompany> list() {
        return artKdCompanyService.listAll();
    }


}
